package com.example.aijie.autoreadhelper.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.TargetApi;
import android.content.Intent;
import android.text.TextUtils;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.example.aijie.autoreadhelper.utils.LogUtils;

import java.util.List;

/**
 * 监听新闻类app的service
 */
public class NewsAppMonitorService extends AccessibilityService {

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        LogUtils.i("服务启动：");
        AccessibilityServiceInfo serviceInfo = new AccessibilityServiceInfo();
        serviceInfo.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
        serviceInfo.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
        serviceInfo.packageNames = new String[]{"com.xiangzi.jukandian", "com.songheng.eastnews","com.jiuhuang.news","com.ly.taotoutiao"};
        serviceInfo.notificationTimeout = 100;
        setServiceInfo(serviceInfo);
    }

    @TargetApi(16)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        int eventType = event.getEventType();
        switch (eventType) {
            case AccessibilityEvent.TYPE_VIEW_CLICKED:
                LogUtils.i("界面点击，source：" + event.getSource());
                LogUtils.i("界面点击，class：" + event.getClassName());
                //界面点击
                break;
            case AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED:
                LogUtils.i("界面文字改动：" + event.getSource());
                break;
            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                String className = event.getClassName().toString();
                LogUtils.i("界面改变：" + className);
                if (AutoReadService.appBean != null) {
                    if (isArticleDetail(className)) {
                        // 到新闻详情页面了，开始向下滚动
                        LogUtils.e("到详情了");
                        Intent intent = new Intent(NewsAppMonitorService.this, AutoReadService.class);
                        intent.putExtra(AutoReadService.KEY_FROM_EVENT, AutoReadService.FROM_EVENT.Event_start_read_article);
                        startService(intent);
                    } else if (isAdv(className)) {
                        Intent intent = new Intent(NewsAppMonitorService.this, AutoReadService.class);
                        intent.putExtra(AutoReadService.KEY_FROM_EVENT, AutoReadService.FROM_EVENT.Event_end_adv_and_re_read);
                        startService(intent);
                    }
                }
                break;
        }
    }

    @TargetApi(16)
    private void showAllArticle() {
        // 是网页新闻，点击查看全文，奖励更多
        LogUtils.e("click 2");
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        if (rootNode != null) {
            LogUtils.e("click 3");
            int count = rootNode.getChildCount();
            for (int i = 0; i < count; i++) {
                LogUtils.e("click 4");
                final AccessibilityNodeInfo nodeInfo = rootNode.getChild(i);
                if (nodeInfo == null) {
                    continue;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        clickNode(nodeInfo);
                    }
                }).start();
            }
        }
    }

    @TargetApi(18)
    private void clickNode(AccessibilityNodeInfo nodeInfo) {
        LogUtils.e("click 5");
        // 查看全文，点击更多，是一个RelativeLayout 里包含的ImageView
        List<AccessibilityNodeInfo> nodeInfos = nodeInfo.findAccessibilityNodeInfosByViewId("BAIDU_SSP__wrapper_u3413313_0");
//        List<AccessibilityNodeInfo> nodeInfos = nodeInfo.findAccessibilityNodeInfosByViewId("com.xiangzi.jukandian:id/ll_tool_bar_menu1_layout");
        if (nodeInfos != null && !nodeInfos.isEmpty()) {
            LogUtils.e("click 6");
            nodeInfos.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
        }
    }

    /**
     * 根据类名判断是否是广告页面
     */
    private boolean isAdv(String className) {
        List<String> advPageList = AutoReadService.appBean.getAdvPage();
        for (String page : advPageList) {
            if (TextUtils.equals(className, page)) {
                LogUtils.e("是广告");
                return true;
            }
        }
        return false;
    }

    /**
     * 根据类名判断是否是文章详情页
     */
    private boolean isArticleDetail(String className) {
        List<String> newDetailActivityList = AutoReadService.appBean.getNewsDetailActivity();
        for (String page : newDetailActivityList) {
            if (TextUtils.equals(className, page)) {
                LogUtils.e("是文章详情："+className);
                return true;
            }
        }
        return false;
    }

    /**
     * 是否是列表主页
     */
    private boolean isMainActivity(String className) {
        String mainActivity = AutoReadService.appBean.getHomeActivity();
        return TextUtils.equals(className, mainActivity);
    }

    /**
     * 是否有查看更多的按钮id
     *
     * @return
     */
    private boolean hasReadMoreBtnId() {
        return false;
    }

    @Override
    public void onInterrupt() {
        LogUtils.i("服务停止：");
    }

    @TargetApi(24)
    @Override
    public void onDestroy() {
        disableSelf();
        LogUtils.i("服务销毁：");
        super.onDestroy();
    }
}
